package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.constant.PageResult;
import com.leyou.common.exception.domain.ExceptionEnum;
import com.leyou.common.exception.domain.LyException;

import com.leyou.common.utils.BeanHelper;
import com.leyou.item.domian.Sku;
import com.leyou.item.domian.Spu;
import com.leyou.item.domian.SpuDetail;
import com.leyou.item.dto.*;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constant.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constant.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constant.MQConstants.RoutingKey.ITEM_UP_KEY;


@Service
@Transactional
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private AmqpTemplate amqpTemplate;



    public PageResult<SpuDTO> goodsPageQuery(Integer page, Integer rows, String key, Boolean saleable) {
        //封装分页信息
        PageHelper.startPage(page, rows);
        //封装查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(key)) {
            criteria.andLike("name", "%" + key + "%");

        }
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }

        //分页查询
        List<Spu> spus = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spus)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);

        }
        //得到pageHelper的分页对象
        PageInfo<Spu> pageInfo = new PageInfo<>(spus);
        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(spus, SpuDTO.class);
        //对SpuDTO中的分类名称和品牌名称做处理
        handlerCategoryNamesAndBrandName(spuDTOS);


        //封装自定义的分页对象
        PageResult<SpuDTO> pageResult = new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), spuDTOS);

        return pageResult;

    }

    private void handlerCategoryNamesAndBrandName(List<SpuDTO> spuDTOS) {
        spuDTOS.forEach(spuDTO -> {
            //得到分类集合中名称的拼接
            String categoryNames = categoryService.findByCategorysByIds(spuDTO.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("|"));
            spuDTO.setCategoryName(categoryNames);
            //得到品牌名称
            String brandname = brandService.findBrandById(spuDTO.getBrandId()).getName();
            spuDTO.setBrandName(brandname);

        });

    }

    public void saveGoods(SpuDTO spuDTO) {
        List<Sku> skuList = null;
        try {
            //将spuDTO转成pojo
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);


            //设置商品的状态为下架
            spu.setSaleable(false);
            //添加spu
            spuMapper.insertSelective(spu);
            //获取Spu的id
            Long spuId = spu.getId();
            //得到SpuDetail的DTO
            SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
            //给SpuId赋值
            spuDetailDTO.setSpuId(spuId);
            //将SpuDetail的DTO转成pojo
            SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
            //添加spuDetail
            spuDetailMapper.insertSelective(spuDetail);
            //得到SkuDTO的集合
            List<SkuDTO> skuDTOS = spuDTO.getSkus();

            //将sku的dto转成pojo
            List<Sku> skus = BeanHelper.copyWithCollection(skuDTOS, Sku.class);

            //遍历sku集合给属性赋值
            skus.forEach(sku -> {sku.setSpuId(spuId);
            //由于批量添加的sql中没有判空，所以要自己给时间赋值
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());});
            //批量添加Sku
            skuMapper.insertList(skus);
        } catch (Exception e) {
            e.printStackTrace();
           throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }



    }
    //第六天代码
    //商品下架处理（先要下架才能允许修改）
    public void updateSaleable(Long id, Boolean saleable) {
        Spu record=new Spu();
        record.setId(id);
        record.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(record);
        if (count!=1){
            throw  new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //对静态页和索引的维护
        //参数1：exchange,参数二：routingkey参数三：object发送的对象
        String routingKey=saleable?ITEM_UP_KEY:ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME,routingKey,id);
    }





    //根据spu的id查询spuDetail对象(用于回显)
    public SpuDetailDTO findSpuDetailBySpuId(Long id) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(id);
        if (spuDetail==null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);

        }
        return BeanHelper.copyProperties(spuDetail,SpuDetailDTO.class);

    }

    // 根据SpuId查询Sku集合(用于回显)
    public List<SkuDTO> findSkusBySpuId(Long id) {
        Sku record=new Sku();
        record.setSpuId(id);

        List<Sku> skuList = skuMapper.select(record);
        if (CollectionUtils.isEmpty(skuList)){
            throw  new LyException(ExceptionEnum.GOODS_NOT_FOUND);

        }
        return BeanHelper.copyWithCollection(skuList,SkuDTO.class);

    }

     //修改商品
    public void updateGoods(SpuDTO spuDTO) {
        //将dto转换成pojo
        try {
            //修改spu
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
           spuMapper.updateByPrimaryKeySelective(spu);
           //spudetail
            SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
            SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
            //修改spudetail
            spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
            //删除当前Spu下所有Sku
            Sku record=new Sku();
            record.setSpuId(spu.getId());
           skuMapper.delete(record);
            //得到SkuDTO的集合
            List<SkuDTO> skuDTOS = spuDTO.getSkus();
            //将sku的dto转成pojo
            List<Sku> skus = BeanHelper.copyWithCollection(skuDTOS, Sku.class);
            //遍历sku集合给属性赋值
            skus.forEach(sku -> {
                sku.setSpuId(spu.getId());
                //由于批量添加的sql中没有判空，所以要自己给时间赋值
                sku.setCreateTime(new Date());
                sku.setUpdateTime(new Date());
            });
            //批量添加Sku
            skuMapper.insertList(skus);


        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);

        }

    }

   /* public SpuDTO findSpuBySpuId(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu==null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        //根据spuId查询sku集合
        List<SkuDTO> skuDTOS = findSkusBySpuId(id);
        spuDTO.setSkus(skuDTOS);
        //根据spuId查询spudetal
        SpuDetailDTO spuDetailDTO = findSpuDetailBySpuId(id);
        spuDTO.setSpuDetail(spuDetailDTO);
        return spuDTO;


    }*/
    //根据spuId查询Spu对象，要给对象中的sku集合和detail对象赋值
    public SpuDTO findSpuBySpuId(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu==null){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        //根据spuid查询sku集合
        List<SkuDTO> skuDTOS = findSkusBySpuId(id);
        spuDTO.setSkus(skuDTOS);
        //根据spuid查询spuDetail对象
        SpuDetailDTO spuDetailDTO = findSpuDetailBySpuId(id);
        spuDTO.setSpuDetail(spuDetailDTO);
        return spuDTO;
    }

    //在item微服务提供根据sku的id集合查询sku的对象集合的处理
    public List<SkuDTO> findSkusBySkuIds(List<Long> ids) {
        List<Sku> skus = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(skus)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);

        }

        return BeanHelper.copyWithCollection(skus,SkuDTO.class);


    }


    public void minusStock(Map<Long, Integer> map) {
        try {
            map.entrySet().forEach(entry->{
                //要减的sku对象的id
                Long skuId = entry.getKey();
                //减去的数量
                Integer num = entry.getValue();
                //根据skuId做查询
                Sku sku = skuMapper.selectByPrimaryKey(skuId);
                //封装条件
                Sku record = new Sku();
                record.setId(skuId);
                record.setStock(sku.getStock()-num);
                //减库存操作
                skuMapper.updateByPrimaryKeySelective(record);
            });
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
